#include"common.hpp"
#include"Socket.hpp"
#include"protocol.hpp"

void User(char* buff)
{
    std::cout<<"user should: "<<buff<<" ip port"<<std::endl;
    exit(USER_ERR);
}

int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        User(argv[0]);
    }
    std::string ip = argv[1];
    int port = std::stoi(argv[2]);
    //Inetaddr addr(ip,port);
    std::unique_ptr<TcpSocket> client = std::make_unique<TcpSocket>();
    std::unique_ptr<protocol> clientptc = std::make_unique<protocol>();

    //TcpSocket client();
    client->BuideTcpClientSocket(ip,port);
    while(1)
    {
        int x,y;
        char oper;
        std::cout << "Enter x: ";
        if (!(std::cin >> x)) {
            std::cerr << "输入错误，退出循环。\n";
            break;
        }
        std::cout << "Enter y: ";
        if (!(std::cin >> y)) {
            std::cerr << "输入错误，退出循环。\n";
            break;
        }
        std::cout<<"Enter oper: ";
        std::cin>>oper;
        std::cout<<"test"<<std::endl;

        Request req(x,y,oper);
        std::string s = req.Serialize();
        std::string headers = clientptc->Encode(s);
        int n = client->Send(headers);
        //std::cout<<"Send success"<<std::endl;
        LOG(level::DEBUG)<<"Send success";

        std::string rstr;
        int rsz = client->Recv(&rstr);
        if(rsz > 0){
            std::string jsonstr;
            clientptc->Decode(rstr,&jsonstr);

            Respond res;
            res.Deserialize(jsonstr);
            res.CoutResult();
        }
        else if(rsz == 0){
            LOG(level::DEBUG)<<"exit...";
        }
        else{
            LOG(level::WARING)<<"client异常...";
        }
    }


    // while(1)
    // {
    //     std::string str;
    //     std::getline(std::cin,str);
    //     write(client->Getfd(),str.c_str(),str.size());

    //     char buff[512];
    //     ssize_t rs = read(client->Getfd(),buff,sizeof(buff)-1);
    //     if(rs > 0){
    //         buff[rs] = 0;
    //         std::cout<<buff<<std::endl;
    //     }
    // }


    return 0;
}